package edu.usm.roberge.orbitz;

import java.util.Arrays;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.usm.roberge.HttpRequest;

/**
 * The final request for the Orbitz site sequence
 * Retrieves the for the top 3 flights
 */
public class OrbitzResultRequest {
	private final Pattern PRICE_REG_EX = Pattern.compile("<span class=\"airFarePrice\">([^<]+)</span>");
	private final OrbitzData data;
	private final HttpRequest request;
	
	public OrbitzResultRequest(OrbitzData data) {
		this.data = data;
		request = new HttpRequest(data.getResultsUrl());
	}
	
	public List<String> getSortedPrices() {
		SortedSet<String> prices = new TreeSet<String>();
		String response = request.addRequestHeader("Cookie", data.getCookies()).makeRequest();
		processPrices(response, prices);
		
		return Arrays.asList(prices.toArray(new String[0]));
	}

	private void processPrices(String response, SortedSet<String> prices) {
		Matcher matcher = PRICE_REG_EX.matcher(response);
		if (!matcher.find()) {
			// record error
		}
		
		prices.add(matcher.group(1));
		
		while(matcher.find()) {
			prices.add(matcher.group(1));
		}
		
	}
}
